package com.app.service.impl;

import cn.hutool.core.util.StrUtil;
import com.app.mapper.PlantMapper;
import com.app.model.*;
import com.app.service.DepartmentService;
import com.app.service.PlantService;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.vo.NameAndValueVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.ListUtils;
import org.thymeleaf.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Primary
public class PlantServiceImpl implements PlantService {
    @Autowired
    PlantMapper plantMapper;

    @Autowired
    private DepartmentService departmentService;

    @Override
    public PlantModel getPlantById(int id) {
        QueryWrapper<PlantModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select().eq("id", id);
        PlantModel plantModel = plantMapper.selectOne(queryWrapper);
        if (plantModel == null) {
            return null;
        } else {
            return plantModel;
        }
    }

    @Override
    public Page<PlantModel> getPagePlantList(int page, int limit, List<Integer> idList, String model, String departmentName, Integer sortType) {
        QueryWrapper<PlantModel> queryWrapper = new QueryWrapper<>();
        if (idList.size() > 0) {
            queryWrapper.select().in("department_id", idList);
        } else {
            queryWrapper.select();
        }
        if (StrUtil.isNotBlank(departmentName)) {
            queryWrapper.like("department_name", departmentName);
        }
        if (StrUtil.isNotBlank(model)) {
            queryWrapper.like("person_name", model);
        }
        if (sortType == null || sortType == 1) {
            queryWrapper.orderByAsc("serial_number").orderByDesc("create_time");
        } else {
            queryWrapper.orderByDesc("serial_number").orderByDesc("create_time");
        }
        Page<PlantModel> pages = new Page<>();
        pages.setCurrent(page);
        pages.setSize(limit);
        Page<PlantModel> plantList = plantMapper.selectPage(pages, queryWrapper);
        return plantList;
    }

    @Override
    public void update(PlantModel model) {
        plantMapper.updateById(model);
    }

    @Override
    public void insert(PlantModel model) {
        plantMapper.insert(model);
    }

    @Override
    public void delete(int id) {
        plantMapper.deleteById(id);
    }

    @Override
    public Integer plantCount(List<Integer> idsList) {
        QueryWrapper<PlantModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id");
        if (idsList != null && idsList.size() > 0) {
            queryWrapper.in("department_id", idsList);
        }
        Integer plantCount = plantMapper.selectCount(queryWrapper);
        return plantCount;
    }

    @Override
    public List<PlantModel> getStatisticsByIds(List<Integer> idList, String key) {
        QueryWrapper<PlantModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(key, "COUNT(*) as count");
        if (idList.size() != 0) {
            queryWrapper.in("department_id", idList);
        }
        queryWrapper.groupBy(key);
        List<PlantModel> personModelList = plantMapper.selectList(queryWrapper);
        return personModelList;
    }

    @Override
    public List<PlantModel> getPlantByIds(List<Integer> idList) {
        QueryWrapper<PlantModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select().in("id", idList);
        List<PlantModel> personModelList = plantMapper.selectList(queryWrapper);
        return personModelList;
    }

    @Override
    public String insertPlant(List<PlantModel> plantModelList) throws IOException {
        if (plantModelList != null && !plantModelList.isEmpty()) {
            for (int i = 0; i < plantModelList.size(); i++) {
                if (plantModelList.get(i) != null) {
                    String departmentName = plantModelList.get(i).getDepartmentName();
                    DepartmentModel departmentModel = departmentService.getdepByName(departmentName);
//                    if (departmentModel != null) {
//                        plantModelList.get(i).setDepartmentId(departmentModel.getId());
//                    }
                    plantModelList.get(i).setCreateTime(CommonHelp.getNowTimestamp());
                    if (plantModelList.get(i).getIsXxText().equals("有")) {
                        plantModelList.get(i).setIsXx(1);
                    }
                    if (plantModelList.get(i).getIsXxText().equals("无")) {
                        plantModelList.get(i).setIsXx(0);
                    }
                    if (plantModelList.get(i).getIsEngineText().equals("有")) {
                        plantModelList.get(i).setIsEngine(1);
                    }
                    if (plantModelList.get(i).getIsEngineText().equals("无")) {
                        plantModelList.get(i).setIsEngine(0);
                    }
                }
            }
        }
        plantMapper.batchInsertPlant(plantModelList);
        assert plantModelList != null;
        return "技术阵地数据成功导入" + plantModelList.size() + "行。";
    }

    //批量删除场地数据
    @Override
    public Result<Object> deletePlantBatchByIds(String ids) {
        // 参数校验
        if (StringUtils.isEmpty(ids)) {
            return Result.success("参数为空，无需删除");
        }
        List<Integer> idsList = Arrays.stream(ids.split(","))
                .map(Integer::valueOf)
                .collect(Collectors.toList());
        // 批量删除
        if (!ListUtils.isEmpty(idsList)) {
            plantMapper.deleteBatchIds(idsList);
            return Result.success("批量删除成功");
        } else {
            return Result.success("批量删除失败，数据为空");
        }
    }

    /**
     * 技术阵地、厂房饼状图
     *
     * @return
     */
    @Override
    public List<NameAndValueVo> plantPieCount() {
        List<NameAndValueVo> voList = new ArrayList<>();
        int count = 0;
        List<NameAndValueVo> voList1 = plantMapper.plantPieCount();
        if (ListUtils.isEmpty(voList1)) {
            return voList1;
        }
        for (NameAndValueVo vo : voList1) {
            if ("类型未知".equals(vo.getName())) {
                count += vo.getValue();
            } else {
                voList.add(vo);
            }
        }
        if (count != 0) {
            NameAndValueVo vo0 = new NameAndValueVo();
            vo0.setName("类型未知");
            vo0.setValue(count);
            voList.add(vo0);
        }
        return voList;
    }
}
